﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace DataService.Core.Extensions
{
    public static class WhereExpression
    {
        /// <summary>
        /// 合并表达式 expr1 AND expr2
        /// 支持In查找； Guid[] tempArray=new Guid[]{值1,值2}、string[] tempArray=new string[]{值1,值2}
        /// Like查找 
        /// 例：FindAll<PB_File>(x => tempArray.Contains(x.FileID)|| tempArray1.Contains(x.FileName)&&x.FileName.Contains("参数值"));
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expr1"></param>
        /// <param name="expr2"></param>
        /// <returns> expr1 && expr2</returns>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
        {
            if (expr2 == null)
            {
                throw new Exception("expr2为null不能处理");
            }
            if (expr1 == null)
            {
                return expr2;
            }
            ParameterExpression newParameter = Expression.Parameter(typeof(T), "x");
            var visitor = new NewExpressionVisitor(newParameter);
            Expression left = visitor.Visit(expr1.Body);
            Expression right = visitor.Visit(expr2.Body);
            BinaryExpression body = Expression.And(left, right);
            return Expression.Lambda<Func<T, bool>>(body, newParameter);
        }

        /// <summary>
        /// 合并表达式 expr1 or expr2
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expr1"></param>
        /// <param name="expr2"></param>
        /// <returns>expr1||expr2</returns>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
        {
            if (expr2 == null)
            {
                throw new Exception("expr2为null不能处理");
            }
            if (expr1 == null)
            {
                return expr2;
            }
            ParameterExpression newParameter = Expression.Parameter(typeof(T), "x");
            var visitor = new NewExpressionVisitor(newParameter);
            Expression left = visitor.Visit(expr1.Body);
            Expression right = visitor.Visit(expr2.Body);
            BinaryExpression body = Expression.Or(left, right);
            return Expression.Lambda<Func<T, bool>>(body, newParameter);
        }
        /// <summary>
        /// 表达式取非
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expr)
        {
            if (expr == null)
            {
                throw new Exception("null不能处理");
            }
            ParameterExpression newParameter = expr.Parameters[0];
            UnaryExpression body = Expression.Not(expr.Body);
            return Expression.Lambda<Func<T, bool>>(body, newParameter);
        }

        ///// <summary>
        ///// 并且
        ///例 A B  合并成A&&B
        /// Expression<Func<T, bool>> expression=t=>t.字段1.Contains(值1)
        /// expression=expression.MergeAnd<T>(x=>x.字段2==3)
        ///则合并成后 expression=Expression<Func<T, bool>>(t.字段1.Contains(值1)&&t.字段2==3)
        ///// </summary>
        public static Expression<Func<T, bool>> MergeAnd<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        ///// <summary>
        ///// 异或
        ///例 A B  合并成A||B
        /// Expression<Func<T, bool>> expression=t=>t.字段1.Contains(值1)
        /// expression=expression.MergeOr<T>(x=>x.字段2==3)
        ///等效于 expression=Expression<Func<T, bool>>(t.字段1.Contains(值1)||t.字段2==3)
        ///// </summary>
        public static Expression<Func<T, bool>> MergeOr<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }
        /// <summary>
        /// Lambda表达式拼接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="merge"></param>
        /// <returns></returns>
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // 构建参数映射(从第二个参数到第一个参数)
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
            // 用第一个lambda表达式中的参数替换第二个lambda表达式中的参数
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            // 将lambda表达式体的组合应用于第一个表达式中的参数 
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }

    }

    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;

        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="map"></param>
        /// <param name="exp"></param>
        /// <returns></returns>
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }

    }



    public class NewExpressionVisitor : ExpressionVisitor
    {
        public ParameterExpression _NewParameter { get; private set; }
        public NewExpressionVisitor(ParameterExpression param)
        {
            this._NewParameter = param;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            return this._NewParameter;
        }
    }

}
